const Goods = require("../../model/goods");
module.exports = async(req, res) => {
    const { uid, goodsName } = req.body;
    const resData = {
        // data返回的是用户传递过来的数据
        data: req.body,
        meta: {
            code: 200,
            msg: "添加成功!",
        },
    };
    let resArray = [];
    let goods = await Goods.find({ goodsName });
    let flag = false;
    for (let i = 0; i < goods.length; i++) {
        // 要转成字符串后再比较
        // 要用传过来的(即当前登录用户)uid来与数据库中所有商品的uid一一比较
        if (uid == goods[i].uid.toString()) {
            // 如果有相等的uid，证明当前用户已发布过该商品，flag标识为true,后续if判断，根据情况执创建商品数据 或报错
            flag = true;
            break;
        }
    }
    if (flag == false) {
        try {
            await Goods.create(req.body);
        } catch (err) {
            for (item in err.errors) {
                resArray.push(err.errors[item].message);
            }
            resData.meta.code = 400;
            resData.meta.msg = resArray.join(",");
        }
    } else {
        resData.meta.code = 400;
        resData.meta.msg = "您已发布过该商品,不可重复发布!";
    }
    res.send(resData);
};